In [1]:
# Lists

# Lists are created using square brackets.
import numpy as np
xData = [1, 2, 5, 12, -3, 3.4, np.pi, 19, -12]
print(xData)
[1, 2, 5, 12, -3, 3.4, 3.141592653589793, 19, -12]
In [3]:
# You can use 'len' to check the number of elements in a list.
len(xData)
Out[3]:
9
In [4]:
# Here's another list of the same length.
yData = [2, 3, 4, 5, 5, 4, 3, 2, 4]
len(yData)
Out[4]:
9
In [5]:
# You can also automatically generate a list.
x = list(range(11, 22))
print(x)
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
In [6]:
# Using a third option in range, you can specify the increment of the list.
x = list(range(11, 22, 2))
print(x)
y = list(range(22, 11,-1))
print(y)
[11, 13, 15, 17, 19, 21]
[22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12]
In [8]:
# It is possible select specific elements of a list using square brackets.
# Note that the first element is indexed as zero and the nth element is indexed
# as n-1.
print(xData[0])
xData[len(xData) - 1]
1
Out[8]:
-12
In [9]:
# You can also extract a range of values from the list.
xData[1:6]
Out[9]:
[2, 5, 12, -3, 3.4]
In [12]:
# The 'NumPy' module can be used to do algebraic operations on lists and to convert the lists to arrays.
xArray = np.array(xData)
print(xArray)
[  1.           2.           5.          12.          -3.
   3.4          3.14159265  19.         -12.        ]
In [13]:
# Now you can scale the array...
2*xArray
Out[13]:
array([  2.        ,   4.        ,  10.        ,  24.        ,
        -6.        ,   6.8       ,   6.28318531,  38.        ,
       -24.        ])
In [14]:
# square each element in the array...
xArray**2
Out[14]:
array([  1.       ,   4.       ,  25.       , 144.       ,   9.       ,
        11.56     ,   9.8696044, 361.       , 144.       ])
In [15]:
# do element by element addition and products...
yArray = np.array(yData)
print(xArray - yArray)
xArray*yArray
[ -1.          -1.           1.           7.          -8.
  -0.6          0.14159265  17.         -16.        ]
Out[15]:
array([  2.        ,   6.        ,  20.        ,  60.        ,
       -15.        ,  13.6       ,   9.42477796,  38.        ,
       -48.        ])
In [16]:
# evaluate dot products...
np.dot(xArray, yArray)
Out[16]:
86.02477796076937
In [17]:
# and evaluate cross products of 3-elemnet arrays (among other things)
x3 = np.array([1, 2, 3])
y3 = np.array([6, 5, 4])
np.cross(x3, y3)
Out[17]:
array([-7, 14, -7])